/**
 * This program is free software under the terms and services of the GNU
 * General Public License as published by the Free Software Foundation, either version 3 of the
 * License, or (at your opinion) any later version
 *
 * This program is distributed in the hope that it will be useful, but without any warranty;
 * even implied warranty of merchantability or fitness for a particular purpose.  See the GNU
 * General Public License for more information
 */

package org.sdnngaming.sdnngaming.core;

import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.*;
import org.sdnngaming.sdnngaming.bukkit.Plugin;

public class PacketManager {

    /**
     * Will store the ProtocolManager instance which we will use to
     * gain access to ProtocolLibrary (man's greatest friend)
     */
    private final ProtocolManager m_pProtocolManager;

    /**
     * The constructor will set up the packet instructions for the server,
     * in case we need to modify the behavior of the packets
     *
     * @param bPlayerInfo - True if we want tab list clear, otherwise false
     */
    public PacketManager (boolean bPlayerInfo){
        m_pProtocolManager = Plugin.getProtocolManager ();

        if (bPlayerInfo){
            m_pProtocolManager.addPacketListener (new PacketAdapter (Plugin.getInstance (),
                    ConnectionSide.SERVER_SIDE, ListenerPriority.NORMAL, new Integer[] { Integer.valueOf (201) }){

                @Override
                public void onPacketSending (final PacketEvent pEvent){
                    if (pEvent.getPacketID () == 201){
                        PacketContainer pContainer = pEvent.getPacket ();
                        String sValue = pContainer.getStrings ().read (0);
                        // Create a unique value to differ our packets from the server's
                        if (sValue.startsWith ("$")) {
                            pContainer.getStrings ().write (0, sValue.substring (1));
                            pEvent.setPacket (pContainer);
                        }else{
                            pEvent.setCancelled (true);
                        }
                    }
                }

            });
        }
    }
}
